#include "game_over_state.h"

const std::string GameOverState::kGameOverID = "GAMEOVER";

void GameOverState::GameOverToMain_() {
    TheGame::instance().get_state_machine()->ChangeState(new MainMenuState());
}

void GameOverState::RestartPlay_() {
    TheGame::instance().get_state_machine()->ChangeState(new PlayState());
}

bool GameOverState::OnEnter() {
    StateParser state_parser;
    if ( !state_parser.ParseState("game.xml", kGameOverID, &game_objects_, &texture_id_list_) ) {
        Log("GameOverState parse failed.");
        return false;
    }

    callbacks_.push_back(0);
    callbacks_.push_back(GameOverToMain_);
    callbacks_.push_back(RestartPlay_);

    setCallbacks(callbacks_);

    Log("entering GameOverState.");
    return true;
}

bool GameOverState::OnExit() {
    for (auto it = game_objects_.begin(); it != game_objects_.end(); ++it) {
        (*it)->Clean();
    }
    game_objects_.clear();

    for (unsigned int i = 0; i < texture_id_list_.size(); ++i) {
        TheTM::instance().ClearFromTextureMap(texture_id_list_[i]);
    }

    Log("exiting GameOverState");
    return true;
}

void GameOverState::Update() {
    for (unsigned int i = 0; i < game_objects_.size(); ++i) {
        game_objects_[i]->Update();
    }
}

void GameOverState::Render() {
    for (unsigned int i = 0; i < game_objects_.size(); ++i) {
        game_objects_[i]->Draw();
    }
}

void GameOverState::setCallbacks(const std::vector<Callback>& callbacks) {
    for (unsigned int i = 0; i < game_objects_.size(); ++i) {
        if ( dynamic_cast<MenuButton*>(game_objects_[i]) ) {
            MenuButton* button = dynamic_cast<MenuButton*>(game_objects_[i]);
            button->setCallback( callbacks[button->getCallbackID()] );
        }
    }
}

